import json
import requests
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

chrome_driver = webdriver.Chrome()
chrome_driver.maximize_window()

cookiestr=''
def login_with_single_id():
    chrome_driver.get("https://www.huxiu.com")
    WebDriverWait(chrome_driver, 8).until(EC.element_to_be_clickable((By.CLASS_NAME, "avatar")))
    login_control = chrome_driver.find_element_by_class_name("avatar")
    login_control.click()
    WebDriverWait(chrome_driver, 15).until(
        EC.element_to_be_clickable((By.XPATH, '//*[@id="app"]/section/div[2]/div/div[1]/div[2]/span')))
    idandpwd_control = chrome_driver.find_element_by_xpath('//*[@id="app"]/section/div[2]/div/div[1]/div[2]/span')
    idandpwd_control.click()
    WebDriverWait(chrome_driver, 15).until(
        EC.element_to_be_clickable((By.XPATH, '//*[@id="app"]/section/div[2]/div/div[1]/div[1]/div/input')))
    id_control = chrome_driver.find_element_by_xpath('//*[@id="app"/section/div[2]/div/div[1]/div[1]/div/input')
    WebDriverWait(chrome_driver, 15).until(
        EC.element_to_be_clickable((By.XPATH, '//*[@id="app"]/section/div[2]/div/div[1]/div[2]/div/input')))
    pwd_control = chrome_driver.find_element_by_xpath('//*[@id="app"]/section/div[2]/div/div[1]/div[2]/div/input')
    id_control.send_keys("用户名")
    pwd_control.send_keys("密码")
    WebDriverWait(chrome_driver, 15).until(
        EC.element_to_be_clickable((By.XPATH, '//*[@id="app"]/section/div[2]/div/button')))
    login_button_control = chrome_driver.find_element_by_xpath('//*[@id="app"]/section/div[2]/div/button')
    login_button_control.click()


def write_cookies():
    cookies = chrome_driver.get_cookies()
    with open("cookies.json", "W") as cookisfile:
        json.dump(cookies, cookisfile)


def read_cookies():
    with open("cookies.json", "r", encoding='utf-8') as cookisfile2:
        cookies = json.loads(cookisfile2.read())
        cookiestr = [item["name"] + "=" + item["value"] for item in cookies]
        print(cookiestr)


def cookie_login():
    url = 'https://www.huxiu.com/member/2388622.html'
    headers = {
        'cookie': cookiestr,
        'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Safari/537.36'
    }
    html = requests.get(url=url, headers=headers)
    print(html.text)


if __name__ == "__main__":
    login_with_single_id()
    write_cookies()
    read_cookies()
    cookie_login()
